package com.gravata.enigma.fragments;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.gravata.enigma.Confirm;
import com.gravata.enigma.R;
import com.gravata.enigma.ReloadDataListener;
import com.gravata.enigma.activities.TelaInicial;
import com.gravata.enigma.adapter.AlphabetListAdapter;
import com.gravata.enigma.adapter.AlphabetListAdapter.Item;
import com.gravata.enigma.adapter.AlphabetListAdapter.Row;
import com.gravata.enigma.adapter.AlphabetListAdapter.Section;
import com.gravata.enigma.model.Bouquet;
import com.gravata.enigma.model.BouquetService;
import com.gravata.enigma.model.Satelite;
import com.gravata.enigma.model.Service;
import com.gravata.enigma.model.Transponder;
import com.gravata.enigma.quickaction.servicos.QuickActionBar;
import com.gravata.enigma.quickaction.servicos.QuickActionIcons;
import com.j256.ormlite.dao.ForeignCollection;

public class ServiceFragment extends ListFragment implements ReloadDataListener{
    private AlphabetListAdapter adapter = new AlphabetListAdapter();
    private GestureDetector mGestureDetector;
    private List<Object[]> alphabet = new ArrayList<Object[]>();
    private HashMap<String, Integer> sections = new HashMap<String, Integer>();
    private int sideIndexHeight;
    private static float sideIndexX;
    private static float sideIndexY;
    private int indexListSize;
    private View rootView;
    private List<Service> selecionados=new ArrayList<Service>();
    private Spinner comboBouquet,comboSatelite,comboTransponder;
    private QuickActionBar qab;

    private boolean loaded=false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_service, container, false);

        mGestureDetector = new GestureDetector(getActivity(), new SideIndexGestureListener());

       // if(savedInstanceState!=null)
        //	servicos=savedInstanceState.getParcelableArrayList("lista");

        rootView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {

            	 if (mGestureDetector.onTouchEvent(event)) {
                     return true;
                 } else {
                     return false;
                 }
            }
        });

        comboSatelite=(Spinner) rootView.findViewById(R.id.combo_satelite);
    	comboSatelite.setAdapter(TelaInicial.sateliteComboAdapter);
        comboSatelite.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapter, View arg1,
					int position, long arg3) {

				if(adapter.getAdapter().getItem(position).getClass().isAssignableFrom(Satelite.class)){
					Satelite satelite=(Satelite) adapter.getAdapter().getItem(position);
					TelaInicial.transponderComboAdapter.setData(new ArrayList<Transponder>(satelite.getTransponders()));

					TelaInicial.servicos=TelaInicial.repositorioService.filtrarPor(satelite);

				}else{
					TelaInicial.servicos=TelaInicial.repositorioService.listar(TelaInicial.profile);
					TelaInicial.transponderComboAdapter.setData(new ArrayList<Transponder>());
				}
				prepareRows();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});

        comboTransponder=(Spinner) rootView.findViewById(R.id.combo_transponder);
        comboTransponder.setAdapter(TelaInicial.transponderComboAdapter);

        comboTransponder.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> adapter, View arg1,
					int position, long arg3) {

				if(adapter.getAdapter().getItem(position).getClass().isAssignableFrom(Transponder.class)){
					Transponder transponder=(Transponder) adapter.getAdapter().getItem(position);

					TelaInicial.servicos=TelaInicial.repositorioService.filtrarPor(transponder);

				}else{

					if(comboSatelite.getSelectedItem().getClass().isAssignableFrom(Satelite.class)){
						Satelite satelite=(Satelite) adapter.getAdapter().getItem(position);
						if(satelite.getId()!=null){
							TelaInicial.servicos=TelaInicial.repositorioService.filtrarPor(satelite);
						}else{
							TelaInicial.servicos=TelaInicial.repositorioService.listar(TelaInicial.profile);
						}
					}else{
						TelaInicial.servicos=TelaInicial.repositorioService.listar(TelaInicial.profile);

					}

				}
				prepareRows();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {

			}
		});
		return rootView;
	}

	@Override
	public void onResume() {
		super.onResume();
		prepareRows();
	}



	@Override
	public void onSaveInstanceState(Bundle outState) {
		//outState.putSerializable("lista" , (Serializable) adapter.getRows());
		//outState.putParcelableArrayList("lista", servicos);
		super.onSaveInstanceState(outState);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
 		super.onActivityCreated(savedInstanceState);

 		ListView listView = getListView();
 		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
 		listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

 			private int count=0;
 			private TextView contador;

 		    @Override
 		    public void onItemCheckedStateChanged(ActionMode mode, int position,
 		                                          long id, boolean checked) {
 		        // Here you can do something when items are selected/de-selected,
 		        // such as update the title in the CAB
 		    	Row row= adapter.getItem(position);

 		    	count=checked?count+1:count-1;
 		    	mode.setTitle(count+"");
 		    	contador.setText(count+"");

 		    	adapter.setSelection(position, checked);
 		    }


 		    @Override
 		    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
 		        // Respond to clicks on the actions in the CAB
 		        switch (item.getItemId()) {
 		            case R.id.menu_add_in_bouquet:
 		            	inserirInBouquet();
 		            	adapter.clearSelection();
 		            	count=0;
 		                mode.finish(); // Action picked, so close the CAB
 		                Toast.makeText(getActivity(), R.string.inserido_sucesso, Toast.LENGTH_LONG).show();
 		                return true;
 		            default:
 		                return false;
 		        }
 		    }

 		    @Override
 		    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
 		        // Inflate the menu for the CAB
 		        MenuInflater inflater = mode.getMenuInflater();
 		        inflater.inflate(R.menu.action, menu);
 		       	LayoutInflater mInflater = LayoutInflater.from(getActivity());
 				View mCustomView = mInflater.inflate(R.layout.actionbar_add_in_bouquet, null);
 		        mode.setCustomView(mCustomView);

 		        comboBouquet= (Spinner) getActivity().findViewById(R.id.actionbar_bouquet);
 		        comboBouquet.setAdapter(TelaInicial.comboBouquetAdapter);

 		        contador=(TextView) getActivity().findViewById(R.id.actionbar_contador);

 		        return true;
 		    }

 		    @Override
 		    public void onDestroyActionMode(ActionMode mode) {
 		        // Here you can make any necessary updates to the activity when
 		        // the CAB is removed. By default, selected items are deselected/unchecked.
 		    	count=0;
 		    	adapter.clearSelection();
 		    }

 		    @Override
 		    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
 		        // Here you can perform updates to the CAB due to
 		        // an invalidate() request
 		        return false;
 		    }
 		});

 		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position,
					long id) {

				qab=new QuickActionBar(view);
				qab.setAnimationStyle(QuickActionBar.GROW_FROM_CENTER);

				Service service = ((Item) adapter.getAdapter().getItem(position)).servico;
				ForeignCollection<BouquetService>bs=service.getBouquets();
				if(bs!=null){
					for(final BouquetService b: bs){

						QuickActionIcons icon=new QuickActionIcons();

						icon.setTitle(b.getBouquet().getName());
						icon.setOnClickListener(new OnClickListener() {

							public void onClick(View v) {
								Confirm confirm=new Confirm(getActivity(), getString(R.string.confirmar_exclusao), getString(R.string.confirmar_exclusao_bouquet), new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog, int which) {
										try {
											TelaInicial.repositorioBouquetService.excluir(b);
											qab.dismiss();
										} catch (SQLException e) {
											e.printStackTrace();
										}

									}
								},new DialogInterface.OnClickListener() {

									public void onClick(DialogInterface dialog, int which) {
										qab.dismiss();
									}
								});

								confirm.show();
							}
						});

						qab.addItem(icon);

					}
				}

				qab.show();

			}
		});


	}

	private void inserirInBouquet(){
		getSelecionados();

		Bouquet bouquet= (Bouquet) comboBouquet.getSelectedItem();
		int ordem=bouquet.getServices().size();
		for(Service service: selecionados){
			BouquetService bs=new BouquetService(bouquet, service, ++ordem);
			try {
				TelaInicial.repositorioBouquetService.inserirOuAtualizar(bs);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

    class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            sideIndexX = sideIndexX - distanceX;
            sideIndexY = sideIndexY - distanceY;

            if (sideIndexX >= 0 && sideIndexY >= 0) {
                displayListItem();
            }

            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }

    private List<Service> getSelecionados(){
    	selecionados=new ArrayList<Service>();
    	SparseBooleanArray checked = getListView().getCheckedItemPositions();
    	int size = checked.size(); // number of name-value pairs in the array
    	for (int i = 0; i < size; i++) {
    	    int key = checked.keyAt(i);
    	    boolean value = checked.get(key);
    	    if(value){
    	    	selecionados.add( ((Item)adapter.getItem(key)).servico);
    	    }
    	}
    	return selecionados;
    }


    private void prepareRows(){

    	Collections.sort(TelaInicial.servicos);

	    alphabet.clear();
        List<Row> rows = new ArrayList<Row>();
        int start = 0;
        int end = 0;
        String previousLetter = null;
        Object[] tmpIndexItem = null;
        Pattern numberPattern = Pattern.compile("[0-9]");

        for (Service servico : TelaInicial.servicos) {
        	if(servico.getName().isEmpty())
        		continue;

            String firstLetter = servico.getName().substring(0, 1);

            // Group numbers together in the scroller
            if (numberPattern.matcher(firstLetter).matches()) {
                firstLetter = "#";
            }

            // If we've changed to a new letter, add the previous letter to the alphabet scroller
            if (previousLetter != null && !firstLetter.equals(previousLetter)) {
                end = rows.size() - 1;
                tmpIndexItem = new Object[3];
                tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
                tmpIndexItem[1] = start;
                tmpIndexItem[2] = end;
                alphabet.add(tmpIndexItem);

                start = end + 1;
            }

            // Check if we need to add a header row
            if (!firstLetter.equals(previousLetter)) {
                rows.add(new Section(firstLetter));
                sections.put(firstLetter, start);
            }

            // Add the country to the list
            rows.add(new Item(servico));
            previousLetter = firstLetter;
        }

        if (previousLetter != null) {
            // Save the last letter
            tmpIndexItem = new Object[3];
            tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
            tmpIndexItem[1] = start;
            tmpIndexItem[2] = rows.size() - 1;
            alphabet.add(tmpIndexItem);
        }

        adapter.setRows(rows);
        setListAdapter(adapter);

        updateList();

    }

  /*  @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        } else {
            return false;
        }
    }*/

    public void updateList() {
    	if(rootView!=null){
	        LinearLayout sideIndex = (LinearLayout) rootView.findViewById(R.id.sideIndex);
	        sideIndex.removeAllViews();
	        indexListSize = alphabet.size();
	        if (indexListSize < 1) {
	            return;
	        }

	        int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);
	        int tmpIndexListSize = indexListSize;
	        while (tmpIndexListSize > indexMaxSize) {
	            tmpIndexListSize = tmpIndexListSize / 2;
	        }
	        double delta;
	        if (tmpIndexListSize > 0) {
	            delta = indexListSize / tmpIndexListSize;
	        } else {
	            delta = 1;
	        }

	        TextView tmpTV;
	        for (double i = 1; i <= indexListSize; i = i + delta) {
	            Object[] tmpIndexItem = alphabet.get((int) i - 1);
	            String tmpLetter = tmpIndexItem[0].toString();

	            tmpTV = new TextView(getActivity());
	            tmpTV.setText(tmpLetter);
	            tmpTV.setGravity(Gravity.CENTER);
	            tmpTV.setTextSize(15);
	            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
	            tmpTV.setLayoutParams(params);
	            sideIndex.addView(tmpTV);
	        }

	        sideIndexHeight = sideIndex.getHeight();

	        sideIndex.setOnTouchListener(new OnTouchListener() {
	            @Override
	            public boolean onTouch(View v, MotionEvent event) {
	                // now you know coordinates of touch
	                sideIndexX = event.getX();
	                sideIndexY = event.getY();

	                // and can display a proper item it country list
	                displayListItem();

	                return false;
	            }
	        });
	        loaded=true;
    	}
    }

    public void displayListItem() {
        LinearLayout sideIndex = (LinearLayout) rootView.findViewById(R.id.sideIndex);
        sideIndexHeight = sideIndex.getHeight();
        // compute number of pixels for every side index item
        double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

        // compute the item index for given event position belongs to
        int itemPosition = (int) (sideIndexY / pixelPerIndexItem);

        // get the item (we can do it since we know item index)
        if (itemPosition < alphabet.size()) {
            Object[] indexItem = alphabet.get(itemPosition);
            int subitemPosition = sections.get(indexItem[0]);

            //ListView listView = (ListView) findViewById(android.R.id.list);
            getListView().setSelection(subitemPosition);
        }
    }

	@Override
	public void onReloadData() {
		loaded=false;
		prepareRows();
		comboSatelite.setAdapter(TelaInicial.sateliteComboAdapter);
		comboTransponder.setAdapter(TelaInicial.transponderComboAdapter);
	}

	@Override
	public void onFealoadData(List<?> list) {
		// TODO Auto-generated method stub

	}


}
